package com.gupao.jly521.proxy.cglib;

import com.gupao.jly521.entity.Person;
import com.gupao.jly521.entity.ProgramPerson;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author Jly
 * @date 2018/8/22  17:21
 */
public class CglibProxy implements MethodInterceptor {

    public Object getInstance(Class<?> clazz){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("cglib 动态代理执行前！！！");
        Object obj = methodProxy.invokeSuper(o,objects);
        System.out.println("cglib 动态代理执行后！！！");
        if(obj != null){
            return obj;
        }
        return null;
    }

    public static void main(String[] args) {
        Person person = (Person) new CglibProxy().getInstance(ProgramPerson.class);
        person.findJob();
        System.out.println("------------------------");
//        System.out.println(person.findJob());
    }
}
